package com.sondon.mayi.activity;

import java.util.ArrayList;

import org.androidannotations.annotations.AfterViews;
import org.androidannotations.annotations.Click;
import org.androidannotations.annotations.EActivity;
import org.androidannotations.annotations.OnActivityResult;
import org.androidannotations.annotations.ViewById;
import org.apache.http.Header;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.LinearLayout.LayoutParams;
import android.widget.RadioGroup;
import android.widget.RadioGroup.OnCheckedChangeListener;
import android.widget.TextView;

import com.loopj.android.http.RequestParams;
import com.loopj.android.http.TextHttpResponseHandler;
import com.sondon.mayi.configs.URLConfigs;
import com.sondon.mayi.entity.AddOrderEntity;
import com.sondon.mayi.entity.Cart;
import com.sondon.mayi.entity.DefaultAddressEntity;
import com.sondon.mayi.entity.MyVoucherEntity;
import com.sondon.mayi.events.AddressEvent;
import com.sondon.mayi.fruit.R;
import com.sondon.mayi.ui.DateTimePickDialogUtil;
import com.sondon.mayi.ui.MyMultipleTopBar;
import com.sondon.mayi.ui.TopBarClickListener;
import com.sondon.mayi.util.AsyncHttpUtil;
import com.sondon.mayi.util.DensityUtil;
import com.sondon.mayi.util.GsonUtil;
import com.sondon.mayi.util.ImageLoaderUtil;
import com.sondon.mayi.util.LogUtil;
import com.sondon.mayi.util.ToastUtils;

import de.greenrobot.event.EventBus;

/**
 * @Project : Fruit
 * @Package : com.sondon.mayi.activity
 * @Class : OrderConfirm
 * @Author : 蔡文锋
 * @DateTime：2015年6月25日 上午12:13:19
 * @Blog：http://blog.csdn.net/caiwenfeng_for_23
 * @Description : { 确认订单 }
 *
 */
@EActivity(R.layout.order_confirm)
public class OrderConfirmActivity extends BaseActivity{
	@ViewById
	MyMultipleTopBar topBar;
	@ViewById
	LinearLayout order_confirm_list_layout;//订单列表layout
	@ViewById
	EditText order_message;//订单留言
	@ViewById
	RadioGroup play_style;//支付方式
	@ViewById
	LinearLayout myvoucher_yuan_layout;//我的代金劵layout
	@ViewById
	TextView myvoucher_yuan;//代金劵金额
	@ViewById
	LinearLayout receive_time_layout;//收货时间layout
	@ViewById
	TextView receive_time;//收货时间
	@ViewById
	LinearLayout receive_address_layout;//收获地址layout
	@ViewById
	TextView receiver;//收货人
	@ViewById
	TextView mobile;//手机
	@ViewById
	TextView address;//收获地址
	@ViewById
	TextView count_goods;//共多少件
	@ViewById
	TextView price;//总价
	@ViewById
	TextView ok;//确认
	
	//我的优惠券返回结果码
	public final int VoucherRequestCode=1122;
	//我的收货地址返回结果码
	public final int AddressRequestCode=2233;
	public String voucher_id="";//代金劵ID
	public String address_id="";//地址ID
	public String order_mobile,accept_name,postcode,province,city,area,order_address;
	public static Integer playID=0;
	public ArrayList<String> goods_id = new ArrayList<String>();;
	public ArrayList<String> goods_nums = new ArrayList<String>();
	
	
 	//初始化
	@SuppressLint("InflateParams")
	@AfterViews
	public void initView(){
		topBar.setTopBarClickListener(new TopBarClickListener() {
			@Override
			public void rightBtnClick() {}
			@Override
			public void leftBtnClick() {
				onBackPressed();
				finish();
			}
		});
		//获取从购物车传过来的物品数据,并初始化布局
		initGoodsDataAndView();
		//获取默认收获地址
		initAddressView();
		//获取代金劵数量
		initVoucherView();
		//选择支付方式监听事件
		play_style.setOnCheckedChangeListener(new PlayStyleChangeListener());
	}
	
	
	


	//点击事件
	@Click({ R.id.myvoucher_yuan_layout, R.id.receive_time_layout,
			R.id.receive_address_layout, R.id.ok })
	public void onClick(View v) {
		switch (v.getId()) {

		case R.id.myvoucher_yuan_layout:// 我的代金劵
			myprefs.is_forResult().put(true);
			openActivityForResult(MyVoucherActivity_.class, null,
					VoucherRequestCode);
			break;

		case R.id.receive_time_layout:// 收货时间
			DateTimePickDialogUtil dateTimePicKDialog = new DateTimePickDialogUtil(
					OrderConfirmActivity.this, "");
			dateTimePicKDialog.dateTimePicKDialog(receive_time);
			break;

		case R.id.receive_address_layout:// 收货地址
			myprefs.is_forResult().put(true);
			openActivityForResult(AddressManagerActivity_.class, null,
					AddressRequestCode);
			break;
		case R.id.ok:
			Order_OK();
			break;
		default:
			break;
		}
	}

	// 代金劵回调
	@OnActivityResult(VoucherRequestCode)
	void onVoucherResult(int resultCode, Intent data) {
		if (resultCode == MyVoucherActivity.resultCode) {
			return;
		} else if (resultCode == MyVoucherActivity.resultCode2) {
			// LogUtil.e(TAG, "onResult  resultCode:"+resultCode);
			this.voucher_id = data.getExtras().getString("voucher_id").trim();
			String value = data.getExtras().getString("value").trim();
			myvoucher_yuan.setText(value + "元");
		}
		myprefs.is_forResult().put(false);
	}

	// 收货地址回调
	@OnActivityResult(AddressRequestCode)
	void onAddressResult(int resultCode, Intent data) {
		if (resultCode == AddressManagerActivity.resultCode) {
			return;
		} else if (resultCode == AddressManagerActivity.resultCode2) {

			this.address_id = data.getExtras().getString("address_id");
			this.accept_name = data.getExtras().getString("receiver");
			this.postcode = data.getExtras().getString("postcode");
			this.order_mobile = data.getExtras().getString("mobile");
			this.province = data.getExtras().getString("province");
			this.city = data.getExtras().getString("city");
			this.area = data.getExtras().getString("area");
			this.order_address = data.getExtras().getString("address");

			receiver.setText(this.accept_name);
			mobile.setText(this.order_mobile);
			address.setText(data.getExtras().getString("address_all"));
		}
		
		myprefs.is_forResult().put(false);
	}
	
	
	//选择支付方式监听事件
	class PlayStyleChangeListener implements OnCheckedChangeListener{
		
		@Override
		public void onCheckedChanged(RadioGroup group, int checkID) {
			switch (checkID) {
			case R.id.zhifubao://支付宝支付
//				ToastUtils.show(context, "支付宝支付");
				OrderConfirmActivity.playID=1;
				break;
			case R.id.weixin://微信支付
//				ToastUtils.show(context, "微信支付");
				OrderConfirmActivity.playID=2;
				break;
			case R.id.daofu://货到付款
//				ToastUtils.show(context, "货到付款");
				OrderConfirmActivity.playID=0;
				break;
			default:
				break;
			}
		}
	};
	
	//点击确认按钮,提交生成订单请求
	public void Order_OK(){
		RequestParams params=new RequestParams();
		params.put("pay_type", playID);//支付方式
		params.put("postscript", order_message.getText().toString().trim());//用户附言
		params.put("mobile", this.order_mobile);
		params.put("address", this.order_address);
		params.put("area", this.area);
		params.put("city", this.city);
		params.put("province", this.province);
		params.put("postcode", this.postcode);
		params.put("accept_name", this.accept_name);
		params.put("accept_time", receive_time.getText().toString());
//		params.put("accept_time", "2015-06-27 14:30");
		params.put("prop", this.voucher_id);//代金劵
		//应接口要求 ,拼接参数
		for (int i = 0; i < this.goods_id.size(); i++) {
			params.put("goods_id["+i+"]", this.goods_id.get(i));
			params.put("goods_nums["+i+"]", this.goods_nums.get(i));
		}
//		params.put("goods_id", this.goods_id);
//		params.put("goods_nums", this.goods_nums);
		
		AsyncHttpUtil.post(URLConfigs.AddOrder_ukey+myprefs.Ukey().get(), params, new TextHttpResponseHandler() {
			
			@Override
			public void onSuccess(int status, Header[] arg1, String json) {
				LogUtil.e(TAG, "addorder  json :"+json);
				if(status==200){
					AddOrderEntity entity=GsonUtil.GetFromJson(json, AddOrderEntity.class);
					if(entity.isStatus()){
						//提交订单成功,跳转到订单页面
//						Bundle bundle=new Bundle();
//						bundle.putInt("position", 1);
//						openActivity(MainTabActivity_.class,bundle);
						myprefs.position().put(1);
						openActivity(MainTabActivity_.class);
						
//						finish();
						
						//直接发送event消息会触发异常: Can not perform this action after onSaveInstanceState
//						EventBus.getDefault().post(new TabHostChangeEvent(1));
						//延迟500ms,再发event消息
//						new Thread(new Runnable() {
//							@Override
//							public void run() {
//								try {
//									Thread.sleep(50);
//								} catch (InterruptedException e) {
//									e.printStackTrace();
//								}
//								EventBus.getDefault().post(new TabHostChangeEvent(1));
//							}
//						}).start();
						
					
					}else{
						ToastUtils.show(context, entity.getMsg());
					}
				}
			}
			
			@Override
			public void onFailure(int arg0, Header[] arg1, String arg2, Throwable arg3) {
				ToastUtils.show(context, R.string.network_unavailable);
			}
		});
	}
	
	//获取从购物车传过来的物品数据,并初始化布局
	@SuppressLint("InflateParams")
	public void initGoodsDataAndView(){
		//获取从购物车页面传过来的数据
		@SuppressWarnings("unchecked")
		ArrayList<Cart> list=(ArrayList<Cart>)getIntent().getSerializableExtra("cartlist_item_checked");
		count_goods.setText("共"+list.size()+"件商品");
		//添加购物信息
		if(list.size()>0){
			//显示货物信息
			order_confirm_list_layout.setVisibility(View.VISIBLE);
//			LogUtil.e(TAG, "OrderConfirm  list size :"+list.size());
			double myPrice=0;//总价
			//布局
			for(int i=0;i<list.size();i++){
				View v=LayoutInflater.from(context).inflate(R.layout.order_confirm_item, null);
				
				ImageView order_confirm_item_img=(ImageView) v.findViewById(R.id.order_confirm_item_img);
				TextView order_confirm_item_name=(TextView) v.findViewById(R.id.order_confirm_item_name);
				TextView order_confirm_item_oneprice=(TextView) v.findViewById(R.id.order_confirm_item_oneprice);
				TextView order_confirm_item_num=(TextView) v.findViewById(R.id.order_confirm_item_num);
				
				order_confirm_item_name.setText(list.get(i).getGoods_info().getName());
				order_confirm_item_oneprice.setText("￥ "+list.get(i).getGoods_info().getPrice());
				order_confirm_item_num.setText("X "+list.get(i).getNum());
				ImageLoaderUtil.SetImgView(list.get(i).getGoods_info().getImg(), order_confirm_item_img);
				
				//向上间距5dp
				LayoutParams layoutParams=new LinearLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT,ViewGroup.LayoutParams.WRAP_CONTENT);
				layoutParams.setMargins(0, DensityUtil.dip2px(context, 5), 0, 0);// 左上右下
				order_confirm_list_layout.addView(v,layoutParams);
				
				myPrice= myPrice+Double.valueOf(list.get(i).getGoods_info().getPrice())*Double.valueOf(list.get(i).getNum());
				
				this.goods_id.add(list.get(i).getGoods_id());
				this.goods_nums.add(list.get(i).getNum());
			}
			//清除无用数据
			list.clear();
			list=null;
			
			//设置总价
			price.setText("￥ :"+myPrice);
			
		}else{
			order_confirm_list_layout.setVisibility(View.GONE);
		}
	}
	
	/**
	* @Author 蔡文锋
	* @Data_Time 2015年7月5日  下午6:20:09
	* @Description {  //获取代金劵数量 }
	 */
	private void initVoucherView() {
		//获取我的优惠券列表
		AsyncHttpUtil.get(URLConfigs.MyVoucher_ukey+myprefs.Ukey().get(), null, new TextHttpResponseHandler() {

			@Override
			public void onSuccess(int status, Header[] arg1, String json) {
				if (status == 200) {
					LogUtil.e(TAG, "myvalucher  json : " + json);
					MyVoucherEntity entity = GsonUtil.GetFromJson(json,
							MyVoucherEntity.class);
					if (entity.isStatus()) {
						if(entity.getList().size()>0){
							myvoucher_yuan_layout.setEnabled(true);
							myvoucher_yuan.setText("有"+entity.getList().size()+"代金券");
						}else {
							myvoucher_yuan_layout.setEnabled(false);
							myvoucher_yuan.setText("没有代金劵");
						}
					}
				}
			}

			@Override
			public void onFailure(int status, Header[] arg1, String json,Throwable arg3) {
				ToastUtils.show(context, R.string.network_unavailable);
			}
		});
	}
	
	//请求获取默认收货地址
	private void initAddressView(){
		AsyncHttpUtil.get(URLConfigs.DefaultAddress_ukey+myprefs.Ukey().get(), null, new TextHttpResponseHandler() {
			
			@Override
			public void onSuccess(int status, Header[] arg1, String json) {
				LogUtil.e(TAG, "DefaultAddress json :"+json);
				if(status == 200){
					DefaultAddressEntity entity=GsonUtil.GetFromJson(json, DefaultAddressEntity.class);
					if(entity.isStatus()){
						EventBus.getDefault().post(new AddressEvent(entity.getInfo()));
					}
				}
			}
			
			@Override
			public void onFailure(int status, Header[] arg1, String arg2, Throwable arg3) {
				ToastUtils.show(context, R.string.network_unavailable);
			}
		});
	}
	
	//EventBus事件
	public void onEventMainThread(AddressEvent event) {
		super.onEventMainThread(event);
		
		this.address_id =event.getAddressinfo().getId();
		this.accept_name =event.getAddressinfo().getAccept_name();
		this.postcode =event.getAddressinfo().getZip();
		this.order_mobile =event.getAddressinfo().getMobile();
		this.province =event.getAddressinfo().getProvince();
		this.city =event.getAddressinfo().getCity();
		this.area =event.getAddressinfo().getArea();
		this.order_address =event.getAddressinfo().getAddress();

		receiver.setText(this.accept_name);
		mobile.setText(this.order_mobile);
		
		if("市辖区".equals(city)||"县".equals(this.city)){
			city="";
		}
		
		String address_all=event.getAddressinfo().getProvince_name()
							+city
							+event.getAddressinfo().getArea_name()
							+event.getAddressinfo().getAddress();
		address.setText(address_all);
	}
}
